<template>
  <div class="container">
    <div class="logo">
      <img v-if="registerLogoUrl" :src="registerLogoUrl" alt="logo" class="height-100" border="0px">
    </div>
    <div v-show="step === 1" class="form-box">
      <el-form class="form" autoComplete="on" :model="enterprise" :rules="rules" ref="form" label-position="left"
        label-width="130px">
        <el-form-item prop="activeCode" label="激活码">
          <el-input name="activeCode" type="text" v-model="enterprise.activeCode" autoComplete="on"
            placeholder="请输入激活码" />
        </el-form-item>
        <el-form-item prop="phone" label="绑定手机号">
          <el-input name="phone" type="text" maxlength="11" v-model="enterprise.phone"
            @keyup.native="phoneEls(enterprise.phone)" autoComplete="on" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item prop="smsCode" label="验证码">
          <el-row>
            <el-col :span="16">
              <el-input name="smsCode" type="text" v-model="enterprise.smsCode" autoComplete="on" placeholder="填写验证码" />
            </el-col>
            <el-col :span="8" class="text-align-r">
              <el-button class="code-btn" :loading="codeBtnLoading" :disabled="disabled" @click="getSmsCode">
                {{ btnTxt }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="password" label="设置密码">
          <el-input name="password" type="password" maxlength="11" v-model="enterprise.password" autoComplete="on"
            placeholder="请输入设置密码" />
        </el-form-item>
        <el-form-item prop="passwordAgain" label="确认密码">
          <el-input name="passwordAgain" type="password" maxlength="11" v-model="enterprise.passwordAgain"
            autoComplete="on" placeholder="请输入确认密码" />
        </el-form-item>
      </el-form>
      <el-button type="primary" class="btn" :loading="loading" @click="regEnterprise">下一步：上传证件资料</el-button>
    </div>
    <div v-show="step === 2" class="form-box biz-box">
      <el-form class="form" autoComplete="on" :model="enterprise" :rules="rules" ref="enterprise" label-position="left"
        label-width="130px">
        <div class="flex">
          <div>
            <el-form-item prop="enterpriseName" label="公司名称">
              <el-input name="enterpriseName" type="text" maxlength="20" v-model="enterprise.enterpriseName"
                autoComplete="on" placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item prop="contactPerson" label="联系人">
              <el-input name="contactPerson" type="text" maxlength="12" v-model="enterprise.contactPerson"
                autoComplete="on" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item prop="email" label="联系邮箱">
              <el-input name="email" type="text" maxlength="30" v-model="enterprise.email" autoComplete="on"
                placeholder="请输入联系邮箱" />
            </el-form-item>
            <el-form-item prop="bankCardNo" label="对公信息">
              <div class="bank-info pad-12">
                <div class="font-18 pad-b-10 tips-bank">设置后用于提现赚取的金额和退款的酬金。</div>
                <el-row class="mar-b-10">
                  <el-col :span="8" class="font-18">
                    对公银行
                  </el-col>
                  <el-col :span="16" class="text-align-r">
                    <el-select v-model="enterprise.bankId" placeholder="请选择">
                      <el-option v-for="item in banks" :key="item.bankId" :label="item.bankName" :value="item.bankId">
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row class="mar-b-10">
                  <el-col :span="8" class="font-18">
                    持卡人姓名
                  </el-col>
                  <el-col :span="16" class="text-align-r">
                    <el-input name="bankAccountName" type="text" maxlength="20" v-model="enterprise.bankAccountName"
                      autoComplete="on" placeholder="请输入持卡人名称" />
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8" class="font-18">
                    开户卡号
                  </el-col>
                  <el-col :span="16" class="text-align-r">
                    <el-input name="bankCardNo" type="number" maxlength="20" v-model="enterprise.bankCardNo"
                      autoComplete="on" placeholder="请输入银行卡号" />
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8" class="font-18">
                    开户支行
                  </el-col>
                  <el-col :span="16" class="text-align-r">
                    <el-input name="bankBranch" v-model="enterprise.bankBranch" autoComplete="on"
                      placeholder="请输入开户支行" />
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
            <el-form-item prop="businessLicenseUrl" label="企业证件">
              <div class="flex">
                <div class="pad-r-10">
                  <div class="tips mar-t-3 text-align-c">营业执照</div>
                  <div class="flex v-align-c">
                    <el-upload action="/api/common/uploadFiles" accept="image/jpeg,image/gif,image/png,image/bmp"
                      list-type="picture-card-auto-m" :before-upload="beforeUploadMain" name="files" :data="token"
                      :show-file-list="false" v-loading="fileLoadingMain" :on-success="handleUploadSuccessMain">
                      <img v-if="enterprise.businessLicenseUrl" :src="enterprise.businessLicenseUrl" width="105px"
                        height="105px">
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                  </div>
                </div>
                <div class="pad-r-10">
                  <div class="tips mar-t-3 text-align-c">开户许可证</div>
                  <div class="flex v-align-c">
                    <el-upload action="/api/common/uploadFiles" accept="image/jpeg,image/gif,image/png,image/bmp"
                      list-type="picture-card-auto-m" :before-upload="beforeUploadOther" name="files" :data="token"
                      :show-file-list="false" v-loading="fileLoadingOther" :on-success="handleUploadSuccessOther">
                      <img v-if="enterprise.openingPermitUrl" :src="enterprise.openingPermitUrl" width="105px"
                        height="105px">
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                  </div>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="mar-l-30 pad-l-18">
            <div class="layer-bar pad-l-15 pad-r-15">
              <agreement></agreement>
            </div>
            <div class="pad-t-15">
              <el-radio v-model="radioAgree" label="1">同意</el-radio>
              <el-radio v-model="radioAgree" label="2">拒绝</el-radio>
            </div>
          </div>
        </div>
      </el-form>
      <div class="flex pad-b-30 biz-btn-box">
        <el-button type="primary" v-if="false" class="btn previous flex-item" :loading="loading" @click="step = 1">上一步
        </el-button>
        <el-button type="primary" class="btn flex-item" :loading="loading" @click="updateEnterprise">确认注册</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import agreement from '@/views/register/agreement'
  import img_logo from '@/assets/images/login-logo-2.png'
  import {
    isvalidatePhone
  } from '@/utils/validate'
  import {
    checkEnterprisePhone,
    regEnterprise,
    saveEnterprise
  } from '@/api/user/enterprise'
  import {
    doCheckRegSmsCode,
    getValidateCode,
    sendSms,
    getConfigByDomain
  } from '@/api/login'
  import {
    listBank
  } from '@/api/common/common'
  export default {
    name: 'register',
    components: {
      agreement
    },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!isvalidatePhone(value)) {
          callback(new Error('请输入手机号码'))
        } else {
          callback()
        }
      }
      return {
        img_logo: img_logo,
        loading: false,
        disabled: true,
        codeBtnLoading: false,
        time: 0,
        enterprise: {
          username: '',
          smsCode: ''
        },
        registerLogoUrl: '', // 注册页logo
        rules: {
          phone: [{
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }],
          smsCode: [{
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          }],
          activeCode: [{
            required: true,
            message: '请填写激活码',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请填写密码',
            trigger: 'blur'
          }],
          passwordAgain: [{
            required: true,
            message: '请确认密码',
            trigger: 'blur'
          }],
          enterpriseName: [{
            required: true,
            message: '请输入公司名称',
            trigger: 'blur'
          }],
          contactPerson: [{
            required: true,
            message: '请输入联系人名称',
            trigger: 'blur'
          }],
          email: [{
            required: true,
            message: '请输入联系人邮箱',
            trigger: 'blur'
          }],
          bankBranch: [{
            required: true,
            message: '请输入开户支行',
            trigger: 'blur'
          }],
          bankCardNo: [{
            required: true,
            message: '请输入对公信息',
            trigger: 'blur'
          }]
        },
        btnTxt: '获取验证码',
        validateCode: '',
        step: 1,
        fileLoadingMain: false,
        fileLoadingOther: false,
        radioAgree: '1',
        banks: [],
        token: {}
      }
    },
    watch: {},
    // 初始化页面
    created() {
      this.init()
    },
    methods: {
      // 获取背景图、logo信息
      getConfigByDomain() {
        const DOMAIN = window.location.host
        getConfigByDomain(DOMAIN).then(response => {
          const res = response.data
          this.registerLogoUrl = res.registerLogoUrl || img_logo
          document.title = res.indexTitle || '众项云企'
          this.$pt.setStorageSync('document.title', document.title)
          this.$pt.setStorageSync('document.ico', res.indexIco)
        }).catch(err => {
          console.log(err)
        })
      },
      phoneEls(val) {
        if (isvalidatePhone(val)) {
          this.disabled = false
        } else {
          this.disabled = true
        }
      },
      init() {
        this.getConfigByDomain()
        if (this.getCurrentPage().query.step) {
          this.step = this.getCurrentPage().query.step * 1
        }
        if (this.getCurrentPage().query.enterpriseId) {
          this.enterprise.enterpriseId = this.getCurrentPage().query.enterpriseId
        }
        if (this.getCurrentPage().query.userCode) {
          this.enterprise.userCode = this.getCurrentPage().query.userCode
        }
        if (this.getCurrentPage().query.versionType) {
          this.enterprise.versionType = this.getCurrentPage().query.versionType
        }
        if (this.getCurrentPage().query.token) {
          this.token.accessToken = this.getCurrentPage().query.token
        }
        listBank().then(response => {
          if (response.isError) return
          this.banks = response.data
        })
      },
      updateEnterprise() {
        if (this.radioAgree !== '1') {
          this.$message.error('请阅读并同意用户协议')
          return
        }
        if (!this.enterprise.enterpriseId) {
          this.$message.error('请先注册')
          return
        }
        if (!this.enterprise.enterpriseName) {
          this.$message.error('请输入公司名称')
          return
        }
        if (!this.enterprise.contactPerson) {
          this.$message.error('请输入联系人名称')
          return
        }
        if (!this.enterprise.email) {
          this.$message.error('请输入联系人邮箱')
          return
        }
        if (!this.enterprise.bankId) {
          this.$message.error('请选择对公银行')
          return
        }
        if (!this.enterprise.bankAccountName) {
          this.$message.error('请输入开户名称')
          return
        }
        if (!this.enterprise.bankCardNo) {
          this.$message.error('请输入开户卡号')
          return
        }
        const that = this
        this.enterprise.accessToken = this.token.accessToken
        // this.enterprise.versionType = 1
        saveEnterprise(this.enterprise).then(response => {
          if (response.isError) return
          const data = {
            token: that.enterprise.accessToken,
            userId: response.data.subUserId,
            enterpriseId: that.enterprise.enterpriseId,
            userCode: that.enterprise.userCode,
            username: that.enterprise.username,
            versionType: that.enterprise.versionType
          }
          that.$store.dispatch('LoginByAnonymous', data).then(() => {
            that.$router.push({
              path: '/'
            })
          })
        })
      },
      regEnterprise() {
        if (!this.enterprise.activeCode) {
          this.$message.error('请输入激活码')
          return
        }
        if (this.enterprise.password !== this.enterprise.passwordAgain) {
          this.$message.error('两次输入密码不一致')
          return
        }
        if (this.enterprise.password.length < 6) {
          this.$message.error('密码长度不能小于6个字符')
          return
        }
        const that = this
        doCheckRegSmsCode(this.enterprise.phone, this.enterprise.smsCode).then(response => {
          if (response.isError) return
          regEnterprise(that.enterprise).then(response => {
            if (response.isError) return
            that.step = 2
            that.token = {
              accessToken: response.data.accessToken
            }
            that.enterprise.enterpriseId = response.data.enterpriseId
            that.enterprise.userId = response.data.userId
            that.enterprise.userCode = response.data.userCode
            that.enterprise.versionType = response.data.versionType
          })
        })
      },
      getSmsCode() {
        const that = this
        if (!isvalidatePhone(this.enterprise.phone)) {
          this.$message.error('手机号码输入有误')
          return false
        }
        getValidateCode(that.enterprise.phone).then(response => {
          if (response.isError) return
          that.validateCode = response.data
          that.codeBtnLoading = true
          checkEnterprisePhone(that.enterprise.phone).then(response => {
            if (response.isError) {
              that.codeBtnLoading = false
              return
            }
            sendSms(that.enterprise.phone, that.validateCode, 1).then((response) => {
              that.codeBtnLoading = false
              if (response.isError) return
              that.time = 60
              that.timer()
              this.$message({
                message: '发送成功！',
                type: 'success'
              })
            }, (response) => {
              that.codeBtnLoading = false
              this.$message({
                message: '网络错误',
                type: 'error'
              })
            })
          })
        })
      },
      timer() {
        if (this.time > 0) {
          this.time--
          this.btnTxt = this.time + 's后重新获取'
          this.disabled = true
          setTimeout(this.timer, 1000)
        } else {
          this.time = 0
          this.btnTxt = '获取验证码'
          this.disabled = false
        }
      },
      beforeUploadMain(file) {
        this.beforeUpload(file)
        this.fileLoadingMain = true
      },
      beforeUploadOther(file) {
        this.beforeUpload(file)
        this.fileLoadingOther = true
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUpload(res, file, callback) {
        if (res.code === 101) {
          callback(res)
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      handleUploadSuccessMain(res, file) {
        this.fileLoadingMain = false
        const that = this
        this.handleUpload(res, file, function(res) {
          that.enterprise.businessLicenseUrl = res.data[0]
        })
      },
      handleUploadSuccessOther(res, file) {
        this.fileLoadingOther = false
        const that = this
        this.handleUpload(res, file, function(res) {
          that.enterprise.openingPermitUrl = res.data[0]
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .container {
    background: #f2f2f2;
    min-height: calc(100vh);

    .logo {
      padding: 58px 0 60px 0;
      width: 362px;
      margin: 0 auto;
    }

    .form-box {
      width: 580px;
      margin: 0 auto;
      box-sizing: border-box;

      &.biz-box {
        width: 1126px;
      }

      .layer-bar {
        width: 490px;
        height: 450px;
        overflow-x: hidden;
        overflow-y: auto;
        border: #dcdfe6 2px solid;
      }
    }

    .form {
      background: #ffffff;
      padding: 35px 38px;
      border-radius: 10px;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    }

    .code-btn {
      background: #409eff !important;
      border: 1px solid #409eff !important;
      color: #fff !important;
      border-radius: 10px !important;
      padding: 16px 0px;
      font-size: 12px;
      width: 115px;
      text-align: center;

      &:hover {
        background: #409eff;
        border: 1px solid #409eff;
        color: #fff;
      }

      &[disabled] {
        background: #cccccc !important;
        border: 1px solid #cccccc !important;
      }
    }

    .btn {
      display: block;
      box-sizing: border-box;
      width: 100%;
      margin-top: 30px;
      font-size: 20px;
      border-radius: 8px;
      padding: 17px 20px;

      &.previous {
        background: #ffffff;
        color: #7a6266;
        border: #dcdfe6 1px solid;
      }
    }

    .biz-btn-box {
      width: 508px;
      margin: 0 auto;
    }

    .bank-info {
      background: #f2f2f2;

      .tips-bank {
        color: #999999;
      }

      .el-input__inner {
        height: 36px;
        line-height: 36px;
      }
    }
  }
</style>
